/**
 * 问答汇总组件
 * 展示所有问答对，支持编辑和添加问题
 */
import React, { useState } from 'react';
import { Card, List, Button, Space, Input, Modal, Tag, Collapse, message } from 'antd';
import {
  EditOutlined,
  PlusOutlined,
  SaveOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import { useBrainstormStore } from '@/stores/brainstorm.store';
import { brainstormService } from '@/services/brainstorm.service';
import type { Question } from '@/types/brainstorm';
import './style.css';

const { TextArea } = Input;
const { Panel } = Collapse;

export interface QuestionSummaryProps {
  onContinue?: () => void;
  onSaveDraft?: () => void;
  onRestart?: () => void;
}

export const QuestionSummary: React.FC<QuestionSummaryProps> = ({
  onContinue,
  onSaveDraft,
  onRestart,
}) => {
  const { currentSession, updateSession } = useBrainstormStore();
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editAnswer, setEditAnswer] = useState('');
  const [addingQuestion, setAddingQuestion] = useState(false);
  const [newQuestion, setNewQuestion] = useState('');
  const [newAnswer, setNewAnswer] = useState('');

  const questions = currentSession?.questions || [];
  const answeredCount = questions.filter((q) => q.answer && !q.skipped).length;
  const skippedCount = questions.filter((q) => q.skipped).length;

  const handleEdit = (question: Question) => {
    setEditingId(question.id);
    setEditAnswer(question.answer || '');
  };

  const handleSaveEdit = async (questionId: string) => {
    if (!currentSession) return;

    try {
      // 更新Store
      const updatedQuestions = questions.map((q) =>
        q.id === questionId ? { ...q, answer: editAnswer, skipped: false } : q
      );
      updateSession({ questions: updatedQuestions });

      // 保存到后端
      await brainstormService.saveAnswer(currentSession.id, questionId, editAnswer);

      setEditingId(null);
      message.success('答案已更新');
    } catch (error) {
      message.error('保存失败');
      console.error('Save answer failed:', error);
    }
  };

  const handleCancelEdit = () => {
    setEditingId(null);
    setEditAnswer('');
  };

  const handleAddQuestion = async () => {
    if (!currentSession || !newQuestion.trim()) return;

    try {
      const question: Question = {
        id: `custom-${Date.now()}`,
        text: newQuestion.trim(),
        purpose: 'custom' as any,
        explanation: '用户自定义问题',
        recommendedAnswer: '',
        answer: newAnswer.trim(),
        skipped: false,
        order: questions.length,
      };

      // 更新Store
      updateSession({
        questions: [...questions, question],
      });

      // 重置表单
      setNewQuestion('');
      setNewAnswer('');
      setAddingQuestion(false);
      message.success('问题已添加');
    } catch (error) {
      message.error('添加失败');
      console.error('Add question failed:', error);
    }
  };

  const handleRestart = () => {
    Modal.confirm({
      title: '确认重新开始？',
      content: '重新开始将清空所有答案，此操作不可恢复',
      okText: '确认',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: () => {
        if (onRestart) {
          onRestart();
        }
      },
    });
  };

  return (
    <div className="question-summary">
      {/* 统计信息 */}
      <Card className="summary-stats">
        <Space size={32}>
          <div className="stat-item">
            <div className="stat-value">{questions.length}</div>
            <div className="stat-label">总问题数</div>
          </div>
          <div className="stat-item success">
            <div className="stat-value">{answeredCount}</div>
            <div className="stat-label">已回答</div>
          </div>
          <div className="stat-item warning">
            <div className="stat-value">{skippedCount}</div>
            <div className="stat-label">已跳过</div>
          </div>
        </Space>
      </Card>

      {/* 问答列表 */}
      <div className="qa-list">
        <h3>问答记录</h3>
        <Collapse
          defaultActiveKey={questions.map((q) => q.id)}
          expandIconPosition="end"
        >
          {questions.map((question) => (
            <Panel
              key={question.id}
              header={
                <div className="qa-header">
                  <div className="qa-header-left">
                    {question.skipped ? (
                      <CloseCircleOutlined style={{ color: '#ff4d4f', marginRight: 8 }} />
                    ) : (
                      <CheckCircleOutlined style={{ color: '#52c41a', marginRight: 8 }} />
                    )}
                    <span className="qa-question">{question.text}</span>
                  </div>
                  {question.skipped && <Tag color="orange">已跳过</Tag>}
                </div>
              }
            >
              {editingId === question.id ? (
                <div className="qa-edit">
                  <TextArea
                    value={editAnswer}
                    onChange={(e) => setEditAnswer(e.target.value)}
                    rows={4}
                    placeholder="请输入答案..."
                    autoFocus
                  />
                  <Space style={{ marginTop: 12 }}>
                    <Button
                      type="primary"
                      size="small"
                      icon={<SaveOutlined />}
                      onClick={() => handleSaveEdit(question.id)}
                    >
                      保存
                    </Button>
                    <Button size="small" onClick={handleCancelEdit}>
                      取消
                    </Button>
                  </Space>
                </div>
              ) : (
                <div className="qa-answer">
                  <div className="answer-text">
                    {question.answer || <span className="no-answer">未回答</span>}
                  </div>
                  <Button
                    type="link"
                    size="small"
                    icon={<EditOutlined />}
                    onClick={() => handleEdit(question)}
                  >
                    编辑答案
                  </Button>
                </div>
              )}
            </Panel>
          ))}
        </Collapse>
      </div>

      {/* 添加问题 */}
      <div className="add-question-section">
        {addingQuestion ? (
          <Card className="add-question-form">
            <Space direction="vertical" style={{ width: '100%' }}>
              <Input
                placeholder="输入新问题..."
                value={newQuestion}
                onChange={(e) => setNewQuestion(e.target.value)}
                maxLength={200}
                showCount
              />
              <TextArea
                placeholder="输入答案（可选）..."
                value={newAnswer}
                onChange={(e) => setNewAnswer(e.target.value)}
                rows={3}
                maxLength={500}
                showCount
              />
              <Space>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={handleAddQuestion}
                  disabled={!newQuestion.trim()}
                >
                  添加
                </Button>
                <Button onClick={() => setAddingQuestion(false)}>取消</Button>
              </Space>
            </Space>
          </Card>
        ) : (
          <Button
            type="dashed"
            block
            icon={<PlusOutlined />}
            onClick={() => setAddingQuestion(true)}
          >
            添加更多问题
          </Button>
        )}
      </div>

      {/* 底部操作 */}
      <div className="summary-actions">
        <Space size={16}>
          <Button onClick={handleRestart}>重新开始</Button>
          <Button onClick={onSaveDraft}>保存草稿</Button>
          <Button
            type="primary"
            size="large"
            onClick={onContinue}
            disabled={answeredCount === 0}
          >
            继续（生成观点）
          </Button>
        </Space>
      </div>
    </div>
  );
};
